package future;

import java.util.concurrent.*;

public class CompletableFutureUserDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture<Integer> completeFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " -----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(result > 2) {
                int a = 1/0;
            }
            System.out.println("----1秒中后出结果: " + result);
            return result;
        }, threadPool).whenComplete((v, e)->{
           if(e == null) {
               System.out.println("-----计算完成, 更新系统updateValue: " + v);
           }
        }).exceptionally(e->{
            e.printStackTrace();
            System.out.println("异常情况: " + e.getCause() + "\t" + e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + " 先去忙其他任务");

        System.out.println(completeFuture.get());
    }

    private static void m1() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> completeFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " -----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("----1秒中后出结果: " + result);
            return result;
        });

        System.out.println(Thread.currentThread().getName() + " 先去忙其他任务");

        System.out.println(completeFuture.get());
    }

}
